package com.feinno.urcs.group.interop.task;

import com.feinno.rpc.channel.RpcFuture;
import com.feinno.rpc.client.RpcMethodStub;
import com.feinno.urcs.group.api.FXLogicPoolService;
import com.feinno.urcs.group.api.FXUserIndexService;
import com.feinno.urcs.group.api.GroupMessageLogService;
import com.feinno.urcs.group.interop.entity.FXCatalogIndex;
import com.feinno.urcs.group.interop.entity.FetionFileMessageArgs;
import com.feinno.urcs.group.siptask.task.GroupTaskEvents;
import com.feinno.urcs.group.util.DateUtils;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceSetter;
import org.helium.framework.annotations.TaskImplementation;
import org.helium.framework.rpc.LegacyRpcClient;
import org.helium.framework.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Li.Hongbo <lihongbo@feinno.com>
 */
@TaskImplementation(event = GroupTaskEvents.GROUP_FETION_MESSAGE_FILE)
public class FXSendFileTask implements Task<FetionFileMessageArgs> {

	private static final Logger LOGGER = LoggerFactory.getLogger(FXSendFileTask.class);
	private String rpcMethodName = "SendRichText";

	@FieldSetter("${FX_GROUP_SERVICE_XML}")
	private LegacyRpcClient rpcClient;
	@ServiceSetter
	private FXLogicPoolService groupLogicPool;
	@ServiceSetter
	private FXUserIndexService fxUserIndexService;
	@ServiceSetter
	private GroupMessageLogService groupMessageLogService;

	@Override
	public void processTask(FetionFileMessageArgs args) {
		try {
			FXCatalogIndex fxCatalogIndex = fxUserIndexService.getFXCatalogIndex(args.getGroup().getOperatorMobileNo());
			args.getGroup().setOperatorUid(fxCatalogIndex.getUserId());
			args.getGroup().setOperatorLogicPool(fxCatalogIndex.getLogicalPoolId());
//			int userPoolId = fxUserIndexService.getLogicPoolByUserId(args.getGroup().getOperatorUid());
//			args.getGroup().setGroupLogicPool(groupPoolId);
//			args.getGroup().setOperatorLogicPool(userPoolId);
			RpcMethodStub stub = rpcClient.getMethodStub(rpcMethodName);
			RpcFuture future = stub.invoke(args);
			future.addListener(result -> {
				LOGGER.info(String.format("invoke fetion RPC Method:%s,retCode=%s,Args=%s", rpcMethodName, result.getValue().getReturnCode(), args.toJsonObject().toString()));
				groupMessageLogService.fetionFileMessageDownstreamLog(args, result.getValue().getReturnCode().intValue(), "FX RPC return ", DateUtils.getUTCNow());
			});
		} catch (Exception e) {
			groupMessageLogService.fetionFileMessageDownstreamLog(args, 500, "FX RPC error", DateUtils.getUTCNow());
			LOGGER.error(String.format("process  error,Args=%s", args.toJsonObject().toString()), e);
		}
	}
}
